/**
 * 页面跳转逻辑
 */
import { getCurrentInstance } from 'vue'
import { getHomePathByRole } from './auth'
import { safeNavigateTo, safeRedirectTo, safeSwitchTab } from './router-guard'

// 页面路径枚举
export enum PagePath {
  // 认证相关
  LOGIN = '/pages/auth/login',
  ROLE_SELECT = '/pages/auth/role-select',

  // 首页
  HOME = '/pages/index/index',

  // 管理员页面
  ADMIN_DASHBOARD = '/pages/admin/dashboard',
  ADMIN_USER_MANAGE = '/pages/admin/user-list',
  ADMIN_CLASS_MANAGE = '/pages/admin/class-manage',
  ADMIN_SYSTEM_SETTINGS = '/pages/admin/system-settings',
  ADMIN_USER_DETAIL = '/pages/admin/user-detail',
  ADMIN_LOGS = '/pages/admin/logs',

  // 班主任页面
  TEACHER_DASHBOARD = '/pages/teacher/dashboard',
  TEACHER_STUDENT_LIST = '/pages/teacher/student-list',
  TEACHER_STUDENT_RECORD = '/pages/teacher/student-record',
  TEACHER_EXCEL_IMPORT = '/pages/teacher/excel-import',
  TEACHER_STUDENT_DETAIL = '/pages/teacher/student-detail',
  TEACHER_RECORD_CREATE = '/pages/teacher/record-create',

  // 家长页面
  PARENT_DASHBOARD = '/pages/parent/dashboard',
  PARENT_STUDENT_INFO = '/pages/parent/student-info',
  PARENT_RECORD_VIEW = '/pages/parent/record-view',
  PARENT_RECORD_DETAIL = '/pages/parent/record-detail',
  PARENT_SETTINGS = '/pages/parent/settings'
}

/**
 * 导航服务类
 */
export class NavigationService {
  private static instance: NavigationService

  static getInstance(): NavigationService {
    if (!NavigationService.instance) {
      NavigationService.instance = new NavigationService()
    }
    return NavigationService.instance
  }

  /**
   * 跳转到登录页
   */
  async toLogin(): Promise<void> {
    await safeRedirectTo(PagePath.LOGIN)
  }

  /**
   * 跳转到角色选择页
   */
  async toRoleSelect(): Promise<void> {
    await safeNavigateTo(PagePath.ROLE_SELECT)
  }

  /**
   * 跳转到首页
   */
  async toHome(): Promise<void> {
    await safeSwitchTab(PagePath.HOME)
  }

  /**
   * 根据角色跳转到对应的首页
   */
  async toRoleHome(): Promise<void> {
    const app = getCurrentInstance()?.appContext.app
    const auth = app?.config.globalProperties.$auth

    if (auth?.getters?.currentRole?.value) {
      const homePath = getHomePathByRole(auth.getters.currentRole.value)
      await safeRedirectTo(homePath)
    } else {
      await this.toLogin()
    }
  }

  /**
   * 管理员页面导航
   */
  // 跳转到管理员仪表板
  async toAdminDashboard(): Promise<void> {
    await safeNavigateTo(PagePath.ADMIN_DASHBOARD)
  }

  // 跳转到用户管理
  async toUserManage(): Promise<void> {
    await safeNavigateTo(PagePath.ADMIN_USER_MANAGE)
  }

  // 跳转到班级管理
  async toClassManage(): Promise<void> {
    await safeNavigateTo(PagePath.ADMIN_CLASS_MANAGE)
  }

  // 跳转到系统设置
  async toSystemSettings(): Promise<void> {
    await safeNavigateTo(PagePath.ADMIN_SYSTEM_SETTINGS)
  }

  // 跳转到用户详情
  async toUserDetail(userId: string): Promise<void> {
    await safeNavigateTo(`${PagePath.ADMIN_USER_DETAIL}?userId=${userId}`)
  }

  // 跳转到操作日志
  async toLogs(): Promise<void> {
    await safeNavigateTo(PagePath.ADMIN_LOGS)
  }

  /**
   * 班主任页面导航
   */
  // 跳转到班主任仪表板
  async toTeacherDashboard(): Promise<void> {
    await safeNavigateTo(PagePath.TEACHER_DASHBOARD)
  }

  // 跳转到学生列表
  async toStudentList(): Promise<void> {
    await safeNavigateTo(PagePath.TEACHER_STUDENT_LIST)
  }

  // 跳转到学生档案
  async toStudentRecord(): Promise<void> {
    await safeNavigateTo(PagePath.TEACHER_STUDENT_RECORD)
  }

  // 跳转到Excel导入
  async toExcelImport(): Promise<void> {
    await safeNavigateTo(PagePath.TEACHER_EXCEL_IMPORT)
  }

  // 跳转到学生详情
  async toStudentDetail(studentId: string): Promise<void> {
    await safeNavigateTo(`${PagePath.TEACHER_STUDENT_DETAIL}?studentId=${studentId}`)
  }

  // 跳转到创建记录
  async toRecordCreate(studentId?: string): Promise<void> {
    const url = studentId
      ? `${PagePath.TEACHER_RECORD_CREATE}?studentId=${studentId}`
      : PagePath.TEACHER_RECORD_CREATE
    await safeNavigateTo(url)
  }

  /**
   * 家长页面导航
   */
  // 跳转到家长仪表板
  async toParentDashboard(): Promise<void> {
    await safeNavigateTo(PagePath.PARENT_DASHBOARD)
  }

  // 跳转到学生信息
  async toStudentInfo(): Promise<void> {
    await safeNavigateTo(PagePath.PARENT_STUDENT_INFO)
  }

  // 跳转到档案记录
  async toRecordView(): Promise<void> {
    await safeNavigateTo(PagePath.PARENT_RECORD_VIEW)
  }

  // 跳转到记录详情
  async toRecordDetail(recordId: string): Promise<void> {
    await safeNavigateTo(`${PagePath.PARENT_RECORD_DETAIL}?recordId=${recordId}`)
  }

  // 跳转到设置
  async toSettings(): Promise<void> {
    await safeNavigateTo(PagePath.PARENT_SETTINGS)
  }

  /**
   * 通用导航方法
   */
  // 返回上一页
  async navigateBack(delta?: number): Promise<void> {
    return new Promise((resolve) => {
      uni.navigateBack({
        delta: delta || 1,
        success: () => resolve(),
        fail: () => {
          // 如果返回失败，跳转到首页
          this.toHome()
          resolve()
        }
      })
    })
  }

  // 重新启动应用到指定页面
  async reLaunch(url: string): Promise<void> {
    return new Promise((resolve, reject) => {
      uni.reLaunch({
        url,
        success: () => resolve(),
        fail: (error) => {
          console.error('重新启动应用失败:', error)
          reject(error)
        }
      })
    })
  }

  /**
   * 根据操作结果导航
   */
  // 登录成功后导航
  async navigateAfterLogin(role: string): Promise<void> {
    switch (role) {
      case 'ADMIN':
      case 'SCHOOL_ADMIN':
        await this.toAdminDashboard()
        break
      case 'TEACHER':
        await this.toTeacherDashboard()
        break
      case 'PARENT':
        await this.toParentDashboard()
        break
      default:
        await this.toHome()
    }
  }

  // 登出后导航
  async navigateAfterLogout(): Promise<void> {
    await this.reLaunch(PagePath.LOGIN)
  }

  /**
   * 带参数的导航
   */
  async navigateWithParams(url: string, params: Record<string, any>): Promise<void> {
    const queryString = Object.keys(params)
      .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
      .join('&')

    const fullUrl = queryString ? `${url}?${queryString}` : url
    await safeNavigateTo(fullUrl)
  }

  /**
   * 检查并导航到有权限的页面
   */
  async navigateToAccessiblePage(): Promise<void> {
    const app = getCurrentInstance()?.appContext.app
    const auth = app?.config.globalProperties.$auth

    const role = auth?.getters?.currentRole?.value

    switch (role) {
      case 'ADMIN':
      case 'SCHOOL_ADMIN':
        await this.toAdminDashboard()
        break
      case 'TEACHER':
        await this.toTeacherDashboard()
        break
      case 'PARENT':
        await this.toParentDashboard()
        break
      default:
        await this.toLogin()
    }
  }
}

// 导出导航服务实例
export const navigation = NavigationService.getInstance()

// 导出便捷方法（绑定正确的this上下文）
export const toLogin = () => navigation.toLogin()
export const toRoleSelect = () => navigation.toRoleSelect()
export const toHome = () => navigation.toHome()
export const toRoleHome = () => navigation.toRoleHome()
export const toAdminDashboard = () => navigation.toAdminDashboard()
export const toUserManage = () => navigation.toUserManage()
export const toClassManage = () => navigation.toClassManage()
export const toSystemSettings = () => navigation.toSystemSettings()
export const toUserDetail = (userId: string) => navigation.toUserDetail(userId)
export const toLogs = () => navigation.toLogs()
export const toTeacherDashboard = () => navigation.toTeacherDashboard()
export const toStudentList = () => navigation.toStudentList()
export const toStudentRecord = () => navigation.toStudentRecord()
export const toExcelImport = () => navigation.toExcelImport()
export const toStudentDetail = (studentId: string) => navigation.toStudentDetail(studentId)
export const toRecordCreate = (studentId?: string) => navigation.toRecordCreate(studentId)
export const toParentDashboard = () => navigation.toParentDashboard()
export const toStudentInfo = () => navigation.toStudentInfo()
export const toRecordView = () => navigation.toRecordView()
export const toRecordDetail = (recordId: string) => navigation.toRecordDetail(recordId)
export const toSettings = () => navigation.toSettings()
export const navigateBack = (delta?: number) => navigation.navigateBack(delta)
export const reLaunch = (url: string) => navigation.reLaunch(url)
export const navigateAfterLogin = (role: string) => navigation.navigateAfterLogin(role)
export const navigateAfterLogout = () => navigation.navigateAfterLogout()
export const navigateWithParams = (url: string, params: Record<string, any>) => navigation.navigateWithParams(url, params)
export const navigateToAccessiblePage = () => navigation.navigateToAccessiblePage()

// 默认导出导航服务
export default navigation